package com.zixi.ai.framework.dao.spec;

import com.zixi.ai.common.enums.DataStatus;
import com.zixi.ai.framework.entity.ExtBaseEntity;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root;
import lombok.Setter;
import org.springframework.data.jpa.domain.Specification;

import java.util.ArrayList;
import java.util.List;

/**
 * @author mqiqe
 */
public class MySpecification<T> implements Specification<T>{
	private final List<Criterion> criteria = new ArrayList<>();
    @Setter
    private boolean ignoreDelFlag = false;
    @Override
    public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query,
                                 CriteriaBuilder builder) {
        if (!ignoreDelFlag) {
            if (ExtBaseEntity.class.isAssignableFrom(root.getModel().getJavaType())) {
                this.add(Restrictions.eq("delFlag", DataStatus.NO.getCode()));
            }
        }
        if (!criteria.isEmpty()) {
            List<Predicate> predicates = new ArrayList<>();  
            for(Criterion c : criteria){
                predicates.add(c.toPredicate(root, query,builder));  
            }  
            // 将所有条件用 and 联合起来  
            return builder.and(predicates.toArray(new Predicate[0]));
        }  
        return builder.conjunction();  
    }  
    /** 
     * 增加简单条件表达式 
     */  
    public MySpecification<T> add(Criterion criterion){
        if(criterion!=null){  
            criteria.add(criterion);
        }  
        return this;
    }

    /**
     * 不需要进行权限过滤
     */
    public  static <T> MySpecification<T> builder(){
        return new MySpecification<>();
    }
}  